package com.submit.demo.service.impl;

import com.submit.demo.model.Admin;
import com.submit.demo.model.Collector;
import com.submit.demo.model.LoginLog;
import com.submit.demo.model.Submitter;
import com.submit.demo.repository.AdminRepository;
import com.submit.demo.repository.CollectorRepository;
import com.submit.demo.repository.LoginLogRepository;
import com.submit.demo.repository.SubmitterRepository;
import com.submit.demo.service.UserService;
import com.submit.demo.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private CollectorRepository collectorRepository;

    @Autowired
    private SubmitterRepository submitterRepository;

    @Autowired
    private LoginLogRepository loginLogRepository;

    @Override
    public Map<String, String> login(String username, String password) {
        String token = null;
        Map<String, String> map = new HashMap<>();
        try{
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            LOGGER.info("密码比对中: {} - {}", password, userDetails.getPassword());
            boolean flag = false;
            if(password.equals(userDetails.getPassword()) || passwordEncoder.matches(password, userDetails.getPassword())) flag = true;

            if(!flag){
                throw new BadCredentialsException("密码或验证码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            Map<String, String> infoMap = insertLoginLog(username);
            map.putAll(infoMap);
        }catch (AuthenticationException e){
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        map.put("token", token);
        return map;
    }

    /**
     * 添加登录记录
     */
    private Map<String, String> insertLoginLog(String username){
        Map<String, String> map = new HashMap<>();
        String url = null;
        String id = null;
        Submitter submitter = submitterRepository.findSubmitterByPhone(username);
        Collector collector = collectorRepository.findCollectorByPhone(username);
        Admin admin = adminRepository.findAdminByUsername(username);
        LoginLog loginLog = new LoginLog();
        if(submitter != null){
            loginLog.setRoleId(2);
            loginLog.setUserId(submitter.getId());
            url = "/subtask";
            id = submitter.getId();
        }else if(collector != null){
            loginLog.setRoleId(1);
            loginLog.setUserId(collector.getId());
            url = "/coltask";
            id = collector.getId();
        }else if(admin != null){
            loginLog.setRoleId(3);
            loginLog.setUserId(admin.getId());
            url = "/admin";
            id = admin.getId();
        }
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(request.getRemoteAddr());
        loginLogRepository.insert(loginLog);
        map.put("url", url);
        map.put("id", id);
        return map;
    }


}
